package com.example.dl645.protocol.strategy;

import com.example.dl645.model.MeterData;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;

/**
 * DDZY22C电表解析策略
 */
@Component
public class Ddzy22cParseStrategy implements MeterParseStrategy {
    @Override
        public MeterData parse(byte[] dataField) {
            MeterData data = new MeterData();
            try {
                // 1. 总电能（正确索引：内部16~20，5字节，小端BCD：46 59 74 05 00 → 对应57459.46）
                if (dataField.length >= 21) {
                    byte[] totalBytes = Arrays.copyOfRange(dataField, 16, 21);
                    data.setPositiveTotal(parseBcdToEnergy(totalBytes, "总电能"));
                } else {
                    data.setPositiveTotal(0.0);
                    throw new RuntimeException("DDZY22C数据域太短，无法提取总电能（需至少21字节）");
                }

                // 2. 尖费率（正确索引：内部21~25，5字节，小端BCD：31 70 27 01 00 → 对应12770.31）
                if (dataField.length >= 26) {
                    byte[] topBytes = Arrays.copyOfRange(dataField, 21, 26);
                    data.setPositiveTop(parseBcdToEnergy(topBytes, "尖费率"));
                } else {
                    data.setPositiveTop(0.0);
                    System.out.println("⚠️ DDZY22C尖费率字段索引越界，暂设为0");
                }

                // 3. 峰费率（正确索引：内部26~30，5字节，小端BCD：00 34 26 07 02 → 对应20726.34）
                if (dataField.length >= 31) {
                    byte[] peakBytes = Arrays.copyOfRange(dataField, 26, 31);
                    data.setPositivePeak(parseBcdToEnergy(peakBytes, "峰费率"));
                } else {
                    data.setPositivePeak(0.0);
                    System.out.println("⚠️ DDZY22C峰费率字段索引越界，暂设为0");
                }

                // 4. 平费率（正确索引：内部31~35，5字节，小端BCD：97 04 39 02 00 → 对应23904.97）
                if (dataField.length >= 36) {
                    byte[] flatBytes = Arrays.copyOfRange(dataField, 31, 36);
                    data.setPositiveFlat(parseBcdToEnergy(flatBytes, "平费率"));
                } else {
                    data.setPositiveFlat(0.0);
                    System.out.println("⚠️ DDZY22C平费率字段索引越界，暂设为0");
                }

                // 5. 谷费率（正确索引：内部36~40，5字节，小端BCD：83 57 00 00 70 → 对应57.83）
                if (dataField.length >= 41) {
                    byte[] valleyBytes = Arrays.copyOfRange(dataField, 36, 41);
                    data.setPositiveValley(parseBcdToEnergy(valleyBytes, "谷费率"));
                } else if (dataField.length >= 37) {
                    byte[] valleyBytes = Arrays.copyOfRange(dataField, 36, dataField.length);
                    valleyBytes = padTo5Bytes(valleyBytes); // 补0到5字节
                    data.setPositiveValley(parseBcdToEnergy(valleyBytes, "谷费率（补0）"));
                } else {
                    data.setPositiveValley(0.0);
                    System.out.println("⚠️ DDZY22C谷费率字段索引越界，暂设为0");
                }

            } catch (Exception e) {
                throw new RuntimeException("DDZY22C解析失败：" + e.getMessage());
            }
            return data;
        }

        private byte[] padTo5Bytes(byte[] bytes) {
            if (bytes.length >= 5) return bytes;
            byte[] padded = new byte[5];
            System.arraycopy(bytes, 0, padded, 0, bytes.length);
            return padded;
        }

        private double parseBcdToEnergy(byte[] bcdLittleBytes, String fieldName) {
            // 1. 小端转大端
            byte[] bcdBigBytes = reverseBytes(bcdLittleBytes);

            // 2. BCD码转十进制字符串
            StringBuilder bcdStr = new StringBuilder();
            for (byte b : bcdBigBytes) {
                int high = (b & 0xF0) >> 4;
                int low = b & 0x0F;
                high = (high > 9) ? 0 : high;
                low = (low > 9) ? 0 : low;
                bcdStr.append(high).append(low);
            }
            String rawBcdStr = bcdStr.toString().trim();
            // 3. 去除前导0
            String noLeadingZeroStr = rawBcdStr.replaceFirst("^0+", "");
            if (noLeadingZeroStr.isEmpty()) {
                System.out.println("ℹ️ " + fieldName + " - 全0数据，返回0.00");
                return 0.00;
            }

            // 4. 去除末尾多余的0，确保最终保留2位小数（整数部分+2位小数）
            String noExtraZeroStr = noLeadingZeroStr;
            while (noExtraZeroStr.length() > 2 && noExtraZeroStr.endsWith("0")) {
                noExtraZeroStr = noExtraZeroStr.substring(0, noExtraZeroStr.length() - 1);
            }
            // 5. 插入小数点（固定2位小数）
            String energyStr;
            if (noExtraZeroStr.length() <= 2) {
                energyStr = "0." + String.format("%02d", Integer.parseInt(noExtraZeroStr));
            } else {
                int pointIndex = noExtraZeroStr.length() - 2;
                energyStr = noExtraZeroStr.substring(0, pointIndex) + "." + noExtraZeroStr.substring(pointIndex);
            }
            // 6. 保留4位小数返回
            double energy = Double.parseDouble(energyStr);
            BigDecimal roundedEnergy = new BigDecimal(energy).setScale(4, RoundingMode.HALF_UP);
            System.out.println("✅ " + fieldName + " - 最终值：" + roundedEnergy.doubleValue());
            return roundedEnergy.doubleValue();
        }

        private byte[] reverseBytes(byte[] bytes) {
            byte[] reversed = new byte[bytes.length];
            for (int i = 0; i < bytes.length; i++) {
                reversed[i] = bytes[bytes.length - 1 - i];
            }
            return reversed;
        }

        @Override
        public String getMeterModel() {
            return "DDZY22C";
        }

        @Override
        public byte[] getDataIdentifier() {
            return new byte[]{(byte) 0x44, (byte) 0x44, (byte) 0x5A, (byte) 0x59};
        }
}